package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test06 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class c1=Class.forName("reflect.User");
        User user=(User)c1.newInstance();   // 过时了的
        System.out.println(user);
        // use Constructor
        Constructor constructor=c1.getDeclaredConstructor(String.class,int.class);
        User user2=(User)constructor.newInstance("halo",18);
        System.out.println(user2);
        // 反射调用方法
        User user3=(User)c1.newInstance();
        Method setName=c1.getDeclaredMethod("setName",String.class);
        // use
        setName.invoke(user3,"haloliu");
        System.out.println(user3.getName());
        System.out.println("=====================");
        // 反射操作属性
        User user4=(User)c1.newInstance();
        Field name=c1.getDeclaredField("name");
        name.setAccessible(true);   // 关闭程序安全检测，可访问私有属性
        name.set(user4,"HaloLiu");
        System.out.println(user4.getName());
    }
}
